$(function(){
	login.init();
});
var login = {
	init:function(){
		login.loginFun();
		login.registerFun();
	},
	loginFun:function(){
		var user_name = getCookie('user_name');
		var user_pwd = getCookie('user_pwd');
		console.log(user_pwd,user_name);
		if(user_name!=='' && user_pwd!==''){
			$(".userName").val(user_name);
			$(".userPwd").val(user_pwd);
		}
		//设置cookie
		  function setCookie(cname, cvalue, exdays) {
		      var d = new Date();
		      d.setTime(d.getTime() + (exdays*24*60*60*1000));
		      var expires = "expires="+d.toUTCString();
		      document.cookie = cname + "=" + escape(cvalue) + "; " + expires;
		  }
		  //获取cookie
		 function getCookie(cname) {
		     var name = cname + "=";
		     var ca = document.cookie.split(';'); //以空格分开两个字符
		     for(var i=0; i<ca.length; i++) {
		         var c = ca[i];
		         while (c.charAt(0)==' ') c = c.substring(1);
		         if (c.indexOf(name) != -1){
		           var cnameValue = unescape(c.substring(name.length, c.length));
		           return cnameValue;
		         } 
		     }
		     return "";
		 }
		 //清除cookie  
		 function clearCookie(cname) {  
		     setCookie(cname, "", -1);  
		 }
		$("#login").click(function(){
			if($('#save_in_cookie').is(':checked')){
				var name = $(".userName").val();
				var pwd = $(".userPwd").val();
				setCookie('user_name',name,7);
				setCookie('user_pwd',pwd,7);
			}
			var name = $(".userName").val();
			var pwd = $(".userPwd").val();
			loginUrl = "/login";
			publicDom.post(loginUrl,{
				name: name,
				pwd: pwd
			},function(response){
				if (response.Code === 0) {
					layer.msg('登录成功');
					localStorage.setItem('db_userName',name);
					$(".turn_to").attr("href","home.html");
				}
				else {
					layer.msg(response.Msg);
				}
			},function(err){
				layer.msg(err.Msg);
			});
		});
	},
	registerFun:function(){
		$("#register").click(function(){
			var name = $("#name").val();
			var pwd = $("#password").val();
			registerUrl = '/registered';
			publicDom.post(registerUrl,{
				name: name,
				pwd: pwd
			},function(response){
				if (response.Code === 0) {
					layer.msg("注册成功");
					$(".turn_to_login").href("login.html");
				}
				else {
					layer.msg(response.Msg);
				}
			},function(err){
				layer.msg(err.Msg);
			});
		})
	}
}